<template>
  <!-- 新增设备/器部件 表单 -->
  <a-modal
    v-model:open="visible"
    :title="isEdit ? '编辑设备/器部件' : '新增设备/器部件'"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="780"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item label="设备/器部件名称：" name="deviceName">
        <a-input
          ref="select"
          v-model:value="form.deviceName"
          class="formInput"
          placeholder="请输入"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="所属厂商：" name="supplierId">
        <a-select
          v-model:value="form.supplierId"
          class="formInput"
          placeholder="请选择"
          @change="changeSupplierType"
          allow-clear
        >
          <a-select-option
            v-for="item in supplierList"
            :value="item.supplierId"
            :key="item.supplierId"
          >
            {{ item.supplierShortName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="所属型号：" name="supplierTypeId">
        <a-select
          v-model:value="form.supplierTypeId"
          class="formInput"
          placeholder="请选择"
          :disabled="!form.supplierId"
          allow-clear
        >
          <a-select-option
            v-for="item in supplierTypeList"
            :value="item.id"
            :key="item.id"
          >
            {{ item.type }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="所属生产厂商：">
        <a-input
          v-model:value="form.producerName"
          :controls="false"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="类别：" name="category">
        <a-select
          ref="select"
          v-model:value="form.category"
          class="formSelect"
          placeholder="请选择"
        >
          <a-select-option :value="1"> 拖动 </a-select-option>
          <a-select-option :value="2"> 非拖动 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="模版类别：" name="modelType">
        <a-select
          ref="select"
          v-model:value="form.modelType"
          class="formSelect"
          placeholder="请选择"
        >
          <a-select-option
            v-for="item in modelTypeList"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="器部件图片：">
        <a-upload
          v-model:file-list="fileList"
          name="file"
          list-type="picture-card"
          class="addEquipUpload"
          accept=".JPEG,.JPG,.PNG"
          :max-count="1"
          :action="uploadUrl"
          :headers="headers"
          method="post"
          :preview-file="previewFile"
          :before-upload="beforeUpload"
          @change="handleUploadChange"
          @remove="handleRemove"
        >
          <div>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import storage from "@/utils/storage"
const $api = inject("$api")
const props = defineProps({
  addEquipVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})
const visible = ref(props.addEquipVisible)
const emits = defineEmits(["update:addEquipVisible"])
const fileList = ref([])
const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
watch(
  () => props.addEquipVisible,
  async (val) => {
    visible.value = val
    if (val) {
      await getModelTypeList()
      await getModelCategoryTypeList()
      await getSupplierTypeTree()
      if (props.isEdit) {
        supplierTypeList.value =
          supplierList.value.filter(
            (item) => item.supplierId === props.rowData.supplierId
          )[0]?.supplierTypeEntities || []

        const res = await $api.fileFindByIds(props.rowData.iconFileId)
        if (res.data && res.data.length) {
          fileList.value = res.data
        }
        form.value = {
          ...props.rowData,
        }
      }
    }
  }
)
const labelCol = { style: { width: "130px" } }
const formRef = ref(null)
const form = ref({
  deviceName: undefined,
  supplierId: undefined,
  supplierTypeId: undefined,
  producerName: undefined,
  category: undefined,
  modelType: undefined,
  iconFileId: undefined,
})
const rules = ref({
  deviceName: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  supplierTypeId: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
    },
  ],
  producerName: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  category: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  modelType: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  supplierId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
})
const supplierList = ref([])
const cancel = () => {
  emits("update:addEquipVisible", false)
  formRef.value.clearValidate()
  form.value = {
    deviceName: undefined,
    supplierId: undefined,
    supplierTypeId: undefined,
    producerName: undefined,
    category: undefined,
    modelType: undefined,
    iconFileId: undefined,
  }
  fileList.value = []
}
const supplierTypeList = ref([])
const changeSupplierType = (id) => {
  form.value.supplierTypeId = null
  supplierTypeList.value =
    supplierList.value.filter((item) => item.supplierId === id)[0]
      ?.supplierTypeEntities || []
}
const getSupplierTypeTree = async () => {
  const res = await $api.supplierTypeTree()
  supplierList.value = res.data
}
const loading = ref(false)
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const params = {
        ...form.value,
      }
      if (props.isEdit) {
        // 编辑带上id
        params.id = props.rowData.id
      }
      loading.value = true
      const res = await $api.model(params, props.isEdit ? "put" : "post")
      loading.value = false
      if (res && res.code === 0) {
        message.success(props.isEdit ? "编辑成功" : "新增成功")
        cancel()
        emits("getModelPage")
      }
    })
    .catch((error) => {
      console.log("error", error)
    })
}
const modelTypeList = ref([])
const getModelTypeList = async () => {
  const res = await $api.modelTypeList()
  if (res && res.code === 0) {
    modelTypeList.value = Object.entries(res.data).map(([key, value]) => ({
      value: Number(key), // 将key转换为数字类型
      label: value,
    }))
  }
}
const equipTypeList = ref([])
const getModelCategoryTypeList = async () => {
  const res = await $api.modelCategoryTypeList()
  if (res && res.code === 0) {
    equipTypeList.value = res.data
  }
}
const uploadUrl = async (val) => {
  return `${$api.uploadAction().url}`
}
const handleUploadChange = (data) => {
  if (data.file?.response?.code === 0) {
    form.value.iconFileId = data.file.response.data.id
  }
}
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 220px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
</style>
<style lang="less">
.addEquipUpload {
  .anticon-eye {
    display: none;
  }
}
</style>
